//! 序列化模块
//! 
//! 提供消息序列化和反序列化的功能，支持Protocol Buffers等格式。

use std::any::{Any, TypeId};
use thiserror::Error;
use std::marker::PhantomData;

/// 序列化错误
#[derive(Debug, Error)]
pub enum SerializationError {
    #[error("类型未注册: {0:?}")]
    TypeNotRegistered(TypeId),
    
    #[error("序列化失败: {0}")]
    SerializationFailed(String),
    
    #[error("反序列化失败: {0}")]
    DeserializationFailed(String),
    
    #[error("类型不匹配: 期望 {expected:?}, 实际 {actual:?}")]
    TypeMismatch {
        expected: TypeId,
        actual: TypeId,
    },
    
    #[error("未知错误: {0}")]
    Unknown(String),
}

/// 类型序列化器特性
pub trait TypeSerializer: Send + Sync {
    /// 序列化类型ID
    fn type_id(&self) -> TypeId;
    
    /// 类型名称
    fn type_name(&self) -> &str;
    
    /// 序列化对象
    fn serialize(&self, obj: Box<dyn Any + Send>) -> Result<Vec<u8>, SerializationError>;
    
    /// 反序列化对象
    fn deserialize(&self, data: &[u8]) -> Result<Box<dyn Any + Send>, SerializationError>;
}

/// 序列化器注册表
#[derive(Default)]
pub struct SerializerRegistry {
    // 类型ID到序列化器的映射
    serializers_by_type: dashmap::DashMap<TypeId, Box<dyn TypeSerializer>>,
    
    // 类型名称到序列化器的映射
    serializers_by_name: dashmap::DashMap<String, Box<dyn TypeSerializer>>,
}

impl SerializerRegistry {
    /// 创建新的序列化器注册表
    pub fn new() -> Self {
        Self {
            serializers_by_type: dashmap::DashMap::new(),
            serializers_by_name: dashmap::DashMap::new(),
        }
    }
    
    /// 注册类型序列化器
    pub fn register(&self, serializer: Box<dyn TypeSerializer>) {
        let type_id = serializer.type_id();
        let type_name = serializer.type_name().to_string();
        
        self.serializers_by_type.insert(type_id, serializer.clone());
        self.serializers_by_name.insert(type_name, serializer);
    }
    
    /// 根据类型ID获取序列化器
    pub fn get_by_type(&self, type_id: TypeId) -> Option<Box<dyn TypeSerializer>> {
        self.serializers_by_type.get(&type_id).map(|s| s.clone())
    }
    
    /// 根据类型名称获取序列化器
    pub fn get_by_name(&self, type_name: &str) -> Option<Box<dyn TypeSerializer>> {
        self.serializers_by_name.get(type_name).map(|s| s.clone())
    }
    
    /// 序列化对象
    pub fn serialize(&self, obj: Box<dyn Any + Send>) -> Result<(String, Vec<u8>), SerializationError> {
        let type_id = obj.type_id();
        
        if let Some(serializer) = self.get_by_type(type_id) {
            let type_name = serializer.type_name().to_string();
            let data = serializer.serialize(obj)?;
            Ok((type_name, data))
        } else {
            Err(SerializationError::TypeNotRegistered(type_id))
        }
    }
    
    /// 反序列化对象
    pub fn deserialize(&self, type_name: &str, data: &[u8]) -> Result<Box<dyn Any + Send>, SerializationError> {
        if let Some(serializer) = self.get_by_name(type_name) {
            serializer.deserialize(data)
        } else {
            Err(SerializationError::DeserializationFailed(format!("类型未注册: {}", type_name)))
        }
    }
}

// 给Box<dyn TypeSerializer>实现Clone特征，以便在HashMap中使用
impl Clone for Box<dyn TypeSerializer> {
    fn clone(&self) -> Self {
        // 注意：这里的克隆是不可实现的，我们使用一个占位符
        // 在实际实现中，需要为每种具体的序列化器提供克隆功能
        panic!("无法克隆TypeSerializer");
    }
}

/// 默认的Protocol Buffers序列化器
/// 
/// 注意：这是一个占位实现，实际项目中需要集成具体的Protocol Buffers库
pub struct ProtoSerializer<T: Any + Send + Sync + 'static> {
    _phantom: PhantomData<T>,
}

impl<T: Any + Send + Sync + 'static> ProtoSerializer<T> {
    pub fn new() -> Self {
        ProtoSerializer {
            _phantom: PhantomData,
        }
    }
}

impl<T: Any + Send + Sync + 'static> TypeSerializer for ProtoSerializer<T> {
    fn type_id(&self) -> TypeId {
        TypeId::of::<T>()
    }
    
    fn type_name(&self) -> &str {
        std::any::type_name::<T>()
    }
    
    fn serialize(&self, obj: Box<dyn Any + Send>) -> Result<Vec<u8>, SerializationError> {
        let type_id = obj.type_id();
        match obj.downcast::<T>() {
            Ok(t) => self.serialize_impl(*t),
            Err(_) => Err(SerializationError::TypeMismatch {
                expected: TypeId::of::<T>(),
                actual: type_id,
            }),
        }
    }
    
    fn deserialize(&self, bytes: &[u8]) -> Result<Box<dyn Any + Send>, SerializationError> {
        self.deserialize_impl(bytes)
            .map(|t| Box::new(t) as Box<dyn Any + Send>)
    }
}

impl<T: Any + Send + Sync + 'static> ProtoSerializer<T> {
    fn serialize_impl(&self, _value: T) -> Result<Vec<u8>, SerializationError> {
        // TODO: 实现实际的序列化
        Ok(vec![])
    }

    fn deserialize_impl(&self, _bytes: &[u8]) -> Result<T, SerializationError> {
        // TODO: 实现实际的反序列化
        unimplemented!()
    }
}

// 以下是一个示例实现，用于简单的消息类型
#[cfg(test)]
mod tests {
    use super::*;
    
    // 简单的测试消息
    #[derive(Debug, Clone, PartialEq)]
    struct TestMessage {
        content: String,
    }
    
    // 简单的序列化器实现
    struct TestSerializer;
    
    impl TypeSerializer for TestSerializer {
        fn type_id(&self) -> TypeId {
            TypeId::of::<TestMessage>()
        }
        
        fn type_name(&self) -> &str {
            "TestMessage"
        }
        
        fn serialize(&self, obj: Box<dyn Any + Send>) -> Result<Vec<u8>, SerializationError> {
            let msg = obj.downcast::<TestMessage>()
                .map_err(|_| SerializationError::TypeMismatch {
                    expected: TypeId::of::<TestMessage>(),
                    actual: obj.type_id(),
                })?;
            
            // 简单地序列化为JSON字符串
            let content = msg.content.clone();
            Ok(content.as_bytes().to_vec())
        }
        
        fn deserialize(&self, data: &[u8]) -> Result<Box<dyn Any + Send>, SerializationError> {
            let content = String::from_utf8(data.to_vec())
                .map_err(|e| SerializationError::DeserializationFailed(e.to_string()))?;
            
            Ok(Box::new(TestMessage { content }))
        }
    }
    
    impl Clone for TestSerializer {
        fn clone(&self) -> Self {
            Self
        }
    }
    
    #[test]
    fn test_serialization() {
        // 创建注册表
        let registry = SerializerRegistry::new();
        
        // 注册序列化器
        registry.register(Box::new(TestSerializer));
        
        // 创建测试消息
        let msg = TestMessage {
            content: "Hello, world!".to_string(),
        };
        
        // 序列化
        let (type_name, data) = registry.serialize(Box::new(msg.clone()))
            .expect("序列化失败");
        
        assert_eq!(type_name, "TestMessage");
        
        // 反序列化
        let deserialized = registry.deserialize(&type_name, &data)
            .expect("反序列化失败");
        
        let deserialized_msg = deserialized.downcast::<TestMessage>()
            .expect("类型转换失败");
        
        assert_eq!(*deserialized_msg, msg);
    }
} 